package com.qjc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qjc.entity.TCity;
import com.qjc.entity.TOrder;
import com.qjc.mapper.TCityMapper;
import com.qjc.mapper.TOrderMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shardingsphere.api.hint.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName: TestHintController
 * @Description:
 * @Author: qjc
 * @Date: 2022/4/27 1:12 下午
 */
@RestController
@RequestMapping("/hint")
@Api(value = "/hint", tags = "测试强制路由操作")
public class TestHintController {

    @Autowired
    private TOrderMapper orderMapper;
    @Resource
    private TCityMapper cityMapper;

    @GetMapping("/add")
    @ApiOperation(value = "插入城市信息", notes = "插入城市信息")
    public String addCity(@ApiParam("省份") @RequestParam("province") String province,
                          @ApiParam("城市") @RequestParam("city") String city) {
        HintManager hintManager = HintManager.getInstance();
        // 通过MyHintShardingAlgorithm可知，强制路由到ds-${value%2}
        hintManager.setDatabaseShardingValue(1L);
        for (int i = 0; i < 10; i++) {
            TCity tCity = new TCity();
            tCity.setName(city + i);
            tCity.setProvince(province + i);
            cityMapper.insert(tCity);
        }
        return "SUCCESS";
    }

    @GetMapping("/list")
    @ApiOperation(value = "查询城市信息", notes = "查询城市信息")
    public List<TCity> findCityList() {
        HintManager hintManager = HintManager.getInstance();
        // 通过MyHintShardingAlgorithm可知，强制路由到ds-${value%2}
//        hintManager.setDatabaseShardingValue(1L);
        hintManager.addDatabaseShardingValue("t_city", 1L);
        List<TCity> list = cityMapper.selectList(new QueryWrapper<>());
        list.forEach(city -> {
            System.out.println(city.getId() + " " + city.getName() + " " + city.getProvince());
        });
        return list;
    }

    @GetMapping("/query/hint")
    @ApiOperation(value = "查询订单信息", notes = "查询订单信息")
    public List<TOrder> test2() {
        HintManager hintManager = HintManager.getInstance();
        // 强制路由到库ds-1
        hintManager.addDatabaseShardingValue("t_order", 1L);
        // 强制路由到表t_order_1
        hintManager.addTableShardingValue("t_order", 1L);
        List<TOrder> list = orderMapper.selectList(new QueryWrapper<>());
        list.forEach(order -> {
            System.out.println(order.getOrderId() + " " + order.getOrderNo());
        });
        return list;
    }
}
